<template>
  <!-- 使用pre和code元素保持语义 -->
  <pre class="code-block" :class="themeClass">
    <code :class="languageClass" ref="codeEl">
      <slot /> <!-- 支持插槽内容 -->
    </code>
  </pre>
</template>

<script>
export default {
  props: {
    language: {
      type: String,
      default: 'javascript'
    },
    theme: {
      type: String,
      default: 'default'
    }
  },
  computed: {
    languageClass() {
      return `language-${this.language}`
    },
    themeClass() {
      return `prism-theme-${this.theme}`
    }
  },
  mounted() {
    this.loadPrism().then(() => {
      this.highlightCode();
      // 添加响应式更新
      this.$watch(() => [this.language, this.$slots.default], this.highlightCode)
    });
  },
  methods: {
    async loadPrism() {
      if (typeof Prism === 'undefined') {
        await import('prismjs');
        await import(`prismjs/components/prism-${this.language}`);
        await import(`prismjs/themes/prism${this.theme === 'default' ? '' : '-' + this.theme}.css`);
      }
    },
    highlightCode() {
      this.$nextTick(() => {
        if (typeof Prism !== 'undefined' && this.$refs.codeEl) {
          Prism.highlightElement(this.$refs.codeEl);
        }
      });
    }
  }
}
</script>

<style scoped>
.code-block {
  background: inherit !important; /* 继承父级背景色 */
  padding: 1em !important;
  overflow: auto;
}
</style> 